# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
# Licensed under the 【火山方舟】原型应用软件自用许可协议
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     https://www.volcengine.com/docs/82379/1433703
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# AI 写文章，直接发布到wordpress
# 前提：需要打开 server.py ,localhost:8888
# api.tikhub 是自动抓取最新的小红书，公众号搜索新闻，如果需要，则配置自己的key

from openai import OpenAI
import requests
import json
import base64
import random

client = OpenAI(base_url="http://localhost:8888/api/v3/bots", api_key="{API_KEY}")
WORDPRESS_URL = "https://liangdabiao.com/wp-json/wp/v2"
WORDPRESS_USER = "liangdabiao"
WORDPRESS_PASSWORD = "pkHR alPS Goff 1K"

def post_to_wordpress(title, content):
    """
    将文章发布到WordPress
    :param title: 文章标题
    :param content: markdown格式的文章内容
    :return: 响应结果
    """
    # 将markdown转换为HTML
    try:
        import markdown
        html_content = markdown.markdown(content)
    except ImportError:
        print("警告: markdown模块未安装，将直接发送原始内容")
        html_content = content
    
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + base64.b64encode(f"{WORDPRESS_USER}:{WORDPRESS_PASSWORD}".encode()).decode()
    }
    
    data = {
        'title': title,
        'content': html_content,
        'status': 'publish'
    }
    
    response = requests.post(
        f"{WORDPRESS_URL}/posts",
        headers=headers,
        data=json.dumps(data)
    )
    
    return response.json()


def main():

    QUERY1 = """你是一个资深积木乐高专栏作家，写作流程：
1.基于以下新闻，请找出1个和新闻相关的主题（不要关心品牌，年份等细节，主题应该是简单的5个字以内），然后基于每一个新闻主题整理一个图文介绍（包括展示"CoverImgUrl"图片)。例如：新闻"三叉戟的八格车来袭！玛莎拉蒂授权积木实测：咬合力拉满，鲨鱼腮却失踪了？【测评】" ，那么主题就是“八格车”“莎拉蒂”。
2.然后进行至少一次搜索：搜索相关新闻主题进行资料补充（例如，怎样拼装[主题],查找[主题]等等），补充资料也需要图片展示 ，同时整理资料不要复杂（简单补充则可，资料相关就可以，搜集资料能够写出文章就可以，同时每一个主题至少搜集一次补充资料）
3.最后：按以上整理的所有内容写一个吸引人的文章【描写热点主题相关能够让观众感到兴趣和愉快】，文章内容包括今天热点主题介绍+补充的相关知识资料，文章主题结构：【主题1+补充1，主题2+补充2，...】
4.注意：务必要保留搜索到的相关图片，分析主题不要过多关注（品牌，定价，用户评价，具体细节）。
5.现在给你提供今天小红书的积木热点新闻材料：###  

    {value}
    

 ###，"""

    headers_api = {
            'accept': 'application/json',
            'Authorization': 'Bearer xq5oa0Zj+GMAjRQnzU2evyUdwCoyuYHj7+1Uw=='
        }
    url = 'https://api.tikhub.io/api/v1/wechat_mp/web/fetch_mp_article_list?ghid=gh_fde65db448ac&page=1'
    print(f"请求URL：{url}")
    
    try:
        response = requests.get(url, headers=headers_api, verify=False, timeout=30)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None
    response.raise_for_status()
    data = response.json()
    if data.get("code") != 200:
        print(f"API请求失败，状态码：{data.get('code')}，信息：{data.get('message')}")
        exit()
    items = data.get("data", {}).get("list", [])
    # items 是一个包含10个item的数组，请随机选择一个
    item = random.choice(items)
    # TODO 修改item， 只保留Title, Digest, ContentUrl, CoverImgUrl
    # 下载远程图片到OSS并获取新URL
    oss_url = upload_to_oss(item['CoverImgUrl'])
    
    item = {
        'Title': item['Title'],
        'Digest': item['Digest'],
        'ContentUrl': item['ContentUrl'],
        'CoverImgUrl': oss_url
    }
    # json转为 string
    item_str = json.dumps(item, ensure_ascii=False)

    # 把item_str 替换到QUERY1中 value 
    item_str = QUERY1.replace("{value}", item_str)

    print(item_str)
     
    # stream run
    stream_resp = client.chat.completions.create(
        model="test",
        messages=[
            {
                "role": "user",
                "content": item_str,
            }
        ],
        stream=True,
    )

    thinking = False

    article_content = ""
    for chunk in stream_resp:
        if chunk.choices[0].delta.model_extra.get("reasoning_content"):
            if not thinking:
                print("\n----思考过程----\n")
                thinking = True
            content = chunk.choices[0].delta.model_extra.get("reasoning_content", "")
            print(content, end="", flush=True)
        elif chunk.choices[0].delta.content:
            if thinking:
                print("\n----输出回答----\n")
                thinking = False
            print(chunk.choices[0].delta.content, end="", flush=True)
            article_content += chunk.choices[0].delta.content
    
    # 发布到WordPress
    if article_content:
        # 使用文章内容的前三行作为标题
        title = ' '.join([line.strip() for line in article_content.split('\n')[:3] if line.strip()])
        print("\n\n正在发布到WordPress...")
        result = post_to_wordpress(title, article_content)
        print(f"发布结果: {result}")


if __name__ == "__main__":
    main()
     
